import React, { useCallback, useState } from "react";
import { DatePicker } from "antd";
import moment from "moment";

const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD HH:mm:ss";

/**
 * RangeDisablePicker
 *
 * diff 只可选择支持的时间范围，如 diff="6 months"
 */
export default React.memo(({ value, onChange, diff, ...props }) => {
	const [dates, setDates] = useState(null);
	// const [value, setValue] = useState(null);

	const disabledDate = current => {
		if (!dates) {
			return false;
		}
		if (!diff) {
			return false;
		}
		if (typeof diff !== "string") {
			return false;
		}
		const arr = diff.split(" ");
		if (arr.length !== 2) {
			return false;
		}
		const [num, unit] = arr;
		const tooLate = dates[0] && current.diff(dates[0], unit, true) > num;
		const tooEarly = dates[1] && dates[1].diff(current, unit, true) > num;
		return !!tooEarly || !!tooLate;
	};
	const onOpenChange = open => {
		if (open) {
			setDates([null, null]);
		} else {
			setDates(null);
		}
	};

	return (
		<RangePicker
			format={dateFormat}
			placeholder={["开始日期", "结束日期"]}
			value={dates || value}
			disabledDate={disabledDate}
			onCalendarChange={val => setDates(val)}
			onChange={onChange}
			onOpenChange={onOpenChange}
			onBlur={() => console.log("blur has been triggered")}
			{...props}
		/>
	);
});
